package com.elitel.common.utils.redissonLock;

import com.elitel.common.utils.SpringUtils;
import org.apache.commons.lang3.StringUtils;
import org.redisson.Redisson;
import org.redisson.config.Config;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.context.annotation.Configuration;

/**
 * @author mulis
 */
@Configuration
public class RedissonManager {

    private final Config config = new Config();
    private Redisson redisson = null;

    public Redisson getRedisson() {
        if (redisson == null) {
            synchronized (RedissonManager.class) {
                if (redisson == null) {
                    RedisProperties redisProperties = SpringUtils.getBean(RedisProperties.class);
                    String host = redisProperties.getHost();
                    int port = redisProperties.getPort();
                    String password = redisProperties.getPassword();
                    if (StringUtils.isBlank(password)) {
                        config.useSingleServer()
                                .setAddress(String.format("redis://%s:%s", host, port))
                                .setDatabase(0);
                    } else {
                        config.useSingleServer()
                                .setAddress(String.format("redis://%s:%s", host, port))
                                .setPassword(password)
                                .setDatabase(0);
                    }
                    //看门狗检查锁的续期问题，默认是30秒，可自定设置
                    //config.setLockWatchdogTimeout(15 * 1000l);
                    redisson = (Redisson) Redisson.create(config);
                }
            }
        }
        return redisson;
    }
}
